
const jwt = require('jsonwebtoken');

//生成token

const sign = (option) => {
    //参数 数据 私钥 时效
    return jwt.sign(option,'xxx',{
        expiresIn : 86400
    })//加盐 
}

function verify(){
    return async (ctx,next)=>{
        const jwtToken = ctx.req.headers.authorization
        // console.log(jwtToken);
        if(jwtToken){
            try{const decoded = jwt.verify(jwtToken,'xxx')
            // console.log(decoded);
            if(decoded.id){ //有id则合法
                ctx.userId = decoded.id
                ctx.nickname = decoded.nickname
                await next()
            }
            }catch(error){
                console.log(error.message);
                ctx.body ={
                    code:'809',
                    data:error,
                    msg:'Token失效'
                }
            }
        }else{
            ctx.body ={
                code:'808',
                msg:'请提供Token'
            }
        }
    }
}

module.exports = {
    sign,
    verify
}